package pe.com.rix.taglib.view;

import java.io.IOException;
import java.util.Locale;
import java.util.ResourceBundle;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.JspFragment;
import javax.servlet.jsp.tagext.SimpleTagSupport;

import org.apache.struts.Globals;

import pe.com.cineplanet.config.ConfigValues;

public class Language extends SimpleTagSupport{

	private Boolean saveCurrentPage;
	
	
	@Override
	public void doTag() throws JspException, IOException {
	
		Locale locale = (Locale)getJspContext().getAttribute(Globals.LOCALE_KEY, PageContext.SESSION_SCOPE);
		if(locale==null){
			locale = Locale.getDefault();
		}
		ResourceBundle resource = ResourceBundle.getBundle("pe.com.cineplanet.lang.cineplanet", locale);	
		String localeSelected = "";
		String evalSession = (getSaveCurrentPage()==null || (getSaveCurrentPage()!=null && getSaveCurrentPage()==true))?"true":"false";
		if( locale.getCountry().trim().length()>0)
			localeSelected = locale.getLanguage()+"_"+locale.getCountry();
		else 
			localeSelected = locale.getLanguage();
		
		StringBuffer html = new StringBuffer();
		html.append("<select name='lang' onchange='doSubmit(\"locale.do\",null,{evalSession:\"" + evalSession + "\", lang: this.value});'>");
		for(String[] lang : ConfigValues.languages){
			String selected = "";
			if(lang[0].trim().equals(localeSelected))
				selected = "selected='selected'";
			html.append("<option value='" + lang[0] + "' " + selected + ">" + resource.getString(lang[1])  + "</option>");
		}
		html.append("</select>");
		
		JspWriter out = getJspContext().getOut();
		try {
			JspFragment f = getJspBody();
			if (f != null) {
				f.invoke(out);
			}
			out.print(html.toString());
		} catch (java.io.IOException ex) {
			throw new JspException(ex.getMessage());
		}
	}


	public Boolean getSaveCurrentPage() {
		return saveCurrentPage;
	}


	public void setSaveCurrentPage(Boolean saveCurrentPage) {
		this.saveCurrentPage = saveCurrentPage;
	}
	
	
	
}
